<?php

namespace app\common\lib;

class Rsa
{
    private static $public_key = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC09cVpl8ezw2PmyPAIpdNsdOQE
9J0ejSe8ZKeVqlUqC+y0OYHqeW5dHsWJRvy8Ec98aJA6hdf1bJqdTS162NLChGRP
1is30z9MHOxMUebJvaMetRbKfrTczsk4cWkB3+u6fhWTsY9Ogyecr9zWIKaEuWCn
lKR3JMB8QlVu5yoNAQIDAQAB
-----END PUBLIC KEY-----';

    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {
        return self::$public_key;
    }

    /**
     * 公钥加密
     * @param string $data
     * @return null|string
     */
    public static function publicEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }

        $encrypted = '';

        foreach (str_split($data, 117) as $chunk) {

            openssl_public_encrypt($chunk, $encryptData, self::getPublicKey());

            $encrypted .= $encryptData;
        }

        return base64_encode($encrypted);
    }

    /**
     * 公钥解密
     * @param string $encrypted
     * @return null
     */
    public static function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey())) ? $decrypted : null;
    }

}